# -*- coding:utf-8 -*-
"""
https://www.duitang.com/search/?kw=%E7%BE%8E%E5%A5%B3&type=feed
"""

from urllib.parse import urlencode
import requests
import re
import os


class ImageData(object):
    def __init__(self):
        self.number = 1
        self.url = "https://www.duitang.com/search/?"
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
        }
        self.name = input("请输入你要抓取的类型：")

        # 判断同级目录下是否有某个文件夹，如果没有，则自动创建
        if not os.path.exists(self.name):
            os.mkdir(self.name)

    # 向堆糖网发起请求
    def gat_data_index(self):
        params = {
            "kw": self.name,
            "type": "feed"
        }
        url = self.url + urlencode(params)
        response = requests.get(url, headers=self.headers)
        if response.status_code == 200:
            return response.text
        else:
            return None

    # 使用正则进行数据解析
    def parse_image_url(self, response):
        data_list = re.findall(r'data-iid="" src="(.*?)"', response)      # 使用非贪婪解析
        for url in data_list:
            self.save_image(url)

    # 保存图片
    def save_image(self, url):
        # os.path.splitext(url)[-1]   提取连接后缀
        with open(f"./{self.name}/%d" % self.number + os.path.splitext(url)[-1], "wb") as f:
            resp = requests.get(url).content
            f.write(resp)
            print(f"第{self.number}张图片保存成功")
            self.number += 1

    # 实现主要业务
    def main(self):
        response = self.gat_data_index()
        self.parse_image_url(response)


if __name__ == '__main__':
    image = ImageData()
    image.main()
